package com.newshub.common.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.regex.Pattern;

/**
 * 内容清洗工具类
 * 用于清理HTML标签、特殊字符等，提供干净的文本内容
 */
@Slf4j
@Component
public class ContentCleaner {
    
    // HTML标签正则表达式
    private static final Pattern HTML_TAG_PATTERN = Pattern.compile("<[^>]*>");
    
    // 多余的空白字符正则表达式
    private static final Pattern MULTIPLE_WHITESPACE_PATTERN = Pattern.compile("\\s+");
    
    // 特殊HTML实体正则表达式
    private static final Pattern HTML_ENTITY_PATTERN = Pattern.compile("&[a-zA-Z0-9#]+;");
    
    /**
     * 清洗HTML内容
     * @param content 原始内容
     * @return 清洗后的内容
     */
    public String cleanHtmlContent(String content) {
        if (content == null || content.trim().isEmpty()) {
            return "";
        }
        
        try {
            String cleaned = content;
            
            // 1. 移除HTML标签
            cleaned = removeHtmlTags(cleaned);
            
            // 2. 解码HTML实体
            cleaned = decodeHtmlEntities(cleaned);
            
            // 3. 清理空白字符
            cleaned = cleanWhitespace(cleaned);
            
            // 4. 移除特殊字符
            cleaned = removeSpecialCharacters(cleaned);
            
            return cleaned.trim();
            
        } catch (Exception e) {
            log.warn("内容清洗失败: {}", e.getMessage());
            return content; // 清洗失败时返回原内容
        }
    }
    
    /**
     * 移除HTML标签
     */
    private String removeHtmlTags(String content) {
        return HTML_TAG_PATTERN.matcher(content).replaceAll("");
    }
    
    /**
     * 解码HTML实体
     */
    private String decodeHtmlEntities(String content) {
        return content
                .replace("&nbsp;", " ")
                .replace("&amp;", "&")
                .replace("&lt;", "<")
                .replace("&gt;", ">")
                .replace("&quot;", "\"")
                .replace("&#39;", "'")
                .replace("&apos;", "'")
                .replace("&hellip;", "...")
                .replace("&mdash;", "—")
                .replace("&ndash;", "–")
                .replace("&ldquo;", "\"")
                .replace("&rdquo;", "\"")
                .replace("&lsquo;", "'")
                .replace("&rsquo;", "'");
    }
    
    /**
     * 清理空白字符
     */
    private String cleanWhitespace(String content) {
        // 将多个空白字符替换为单个空格
        String cleaned = MULTIPLE_WHITESPACE_PATTERN.matcher(content).replaceAll(" ");
        
        // 移除行首行尾的空白字符
        return cleaned.trim();
    }
    
    /**
     * 移除特殊字符
     */
    private String removeSpecialCharacters(String content) {
        return content
                .replaceAll("[\\x00-\\x08\\x0B\\x0C\\x0E-\\x1F\\x7F]", "") // 控制字符
                .replaceAll("[\\uFFFD]", "") // 替换字符
                .replaceAll("[\\u200B-\\u200D\\uFEFF]", ""); // 零宽字符
    }
    
    /**
     * 清洗摘要内容（更严格的清洗）
     */
    public String cleanSummary(String summary) {
        if (summary == null || summary.trim().isEmpty()) {
            return "";
        }
        
        String cleaned = cleanHtmlContent(summary);
        
        // 摘要特殊处理：移除链接文本
        cleaned = cleaned.replaceAll("查看全文", "");
        cleaned = cleaned.replaceAll("阅读全文", "");
        cleaned = cleaned.replaceAll("点击查看", "");
        
        // 限制摘要长度
        if (cleaned.length() > 200) {
            cleaned = cleaned.substring(0, 200) + "...";
        }
        
        return cleaned.trim();
    }
    
    /**
     * 清洗标题内容
     */
    public String cleanTitle(String title) {
        if (title == null || title.trim().isEmpty()) {
            return "";
        }
        
        String cleaned = cleanHtmlContent(title);
        
        // 标题特殊处理：移除多余的标点符号
        cleaned = cleaned.replaceAll("[\\s\\p{Punct}]+$", ""); // 移除末尾的标点符号
        
        return cleaned.trim();
    }
}
